package com.cait.dutyfree.action.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ValidationAware;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor implements
		StrutsStatics {

	private static final String USER_HANDLE = "adminUser";
	private static final String LOGIN_ATTEMPT = "loginAttempt";

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		final ActionContext context = invocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) context
				.get(HTTP_REQUEST);
		HttpSession session = request.getSession(true);

		Object user = session.getAttribute(USER_HANDLE);

		// user is not logged in
		if (user == null) {
			Object action = invocation.getAction();
			if (action instanceof ValidationAware) {
				((ValidationAware) action)
						.addActionError("You need to login");
			}
			return "login";
		} else {
			return invocation.invoke();
		}
	}
}
